package com.mimo.logic.session.controller;

import java.util.Optional;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.mimo.common.comet.dto.ZoneDTO;
import com.mimo.common.configuration.broadcast.MultiCastRegistry;
import com.mimo.common.result.BaseResult;
import com.mimo.common.result.CommonDTOResult;
import com.mimo.logic.event.UserStatusActionEvent;
import com.mimo.logic.event.UserStatusActionType;
import com.mimo.logic.session.model.SessionInfo;
import com.mimo.logic.session.service.ISessionService;
import com.mimo.logic.user.service.IUserService;

import io.swagger.annotations.ApiOperation;

@Validated
@RestController
@RequestMapping("/session")
public class SessionController {

  @Autowired
  private ISessionService sessionService;

  @Autowired
  private IUserService userService;

  @PostMapping(value = "/expire")
  @ApiOperation(value = "强制一个会话超期", response = BaseResult.class)
  public BaseResult expire(@RequestParam String userId) {
    MultiCastRegistry.INSTANCE
        .publish(new UserStatusActionEvent(this, userService.load(userId), UserStatusActionType.Offline));
    return BaseResult.SUCCESS_RET;
  }

  @PostMapping(value = "/upsert")
  @ApiOperation(value = "更新或者新增一个会话", response = SessionInfo.class)
  public BaseResult upsert(@Valid @RequestBody SessionInfo session) {
    return new CommonDTOResult<>(sessionService.upsert(session));
  }

  @GetMapping(value = "/list")
  public Object listAll() {
    return sessionService.listAll();
  }

  @GetMapping(value = "/load")
  @ApiOperation(value = "查询用户当前会话所在Zone信息", response = ZoneDTO.class)
  public BaseResult loadByUserId(@RequestParam String userId) {
    BaseResult ret = BaseResult.SUCCESS_RET;
    Optional<SessionInfo> opt = sessionService.findSessionByUser(userId);
    if (opt.isPresent()) {
      ret = new CommonDTOResult<>(opt.get().getZone());
    }
    return ret;
  }

}
